package org.uim.cricket.analyzer.parsers.inning.impl;

import org.uim.cricket.analyzer.parsers.inning.InningTotalsParsable;
import org.uim.cricket.entities.inning.InningTotals;
import org.uim.cricket.util.HTMLStringUtils;
import org.uim.cricket.util.MyStringUtils;

public class DefaultInningTotalsParser implements InningTotalsParsable {

	public static int ALLOUT_WICKETS = 10;
	
	@Override
	public InningTotals parseTotals(String source) {
		if (source == null) return null;
		String[] datarows = MyStringUtils.splitInBetween(source, "<td", "</td>");
		
		if (datarows.length < 4) return null;
		
		String tmp = HTMLStringUtils.cleanHTMLTags("<" + datarows[2]);
		InningTotals totals = getTotals(tmp);
		tmp = HTMLStringUtils.cleanHTMLTags("<" + datarows[3]);
		totals.setRuns(Integer.parseInt(tmp));
		
		return totals;
	}

	private InningTotals getTotals(String src) {
		src = MyStringUtils.replaceAll(src, "", "\\(", "\\)");
		InningTotals totals = new InningTotals();
		String[] extypes = src.split("[;]");
		
		for (int i=0;i<extypes.length;i++) {
			extypes[i] = extypes[i].trim();
			String[] attrib = extypes[i].split("[ ]+");
			
			if (extypes[i].indexOf(" over") >= 0) {
				totals.setOvers(attrib[0]);
			} else if (extypes[i].indexOf(" min") >= 0) {
				totals.setMinutes(Integer.parseInt(attrib[0]));
			} else {
				if (extypes[i].indexOf(" wicket") >= 0) {
					totals.setWickets(Integer.parseInt(attrib[0]));
					if (extypes[i].indexOf(" dec") >= 0) {
						totals.setDeclared(true);
					}
				} else if (extypes[i].indexOf("all out") >= 0) {
					totals.setWickets(ALLOUT_WICKETS);
				}
			}
		}
		
		return totals;
	}
	
}
